import os
import subprocess
from datetime import timedelta

def get_video_duration(input_path):
    """获取视频时长（秒）"""
    cmd = [
        'ffprobe', '-v', 'error',
        '-show_entries', 'format=duration',
        '-of', 'default=noprint_wrappers=1:nokey=1',
        input_path
    ]
    result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
    return float(result.stdout)

def process_video(input_path, output_path, progress_callback=None):
    """视频处理主函数（兼容进度回调）"""
    try:
        # 1. 验证输入文件
        if not os.path.exists(input_path):
            raise FileNotFoundError(f"输入文件不存在: {input_path}")

        duration = get_video_duration(input_path)
        
        # 2. 构建FFmpeg命令（修正版）
        cmd = [
            'ffmpeg',
            '-i', input_path,
            '-f', 'lavfi',
            '-i', f'color=c=black:s=1080x1920:r=30:d={duration}',
            '-filter_complex',
            '[0:v]scale=1080:1920:force_original_aspect_ratio=decrease,'
            'pad=1080:1920:(ow-iw)/2:(oh-ih)/2:color=black,setsar=1[scaled_a];'
            '[1:v]format=rgba,colorchannelmixer=aa=0[scaled_b];'
            '[scaled_a][scaled_b]overlay=eof_action=pass[vout]',
            '-map', '[vout]',
            '-map', '0:a',
            '-c:a', 'copy',
            '-c:v', 'libx264',
            '-x264-params', 'keyint=60',
            '-preset', 'fast',
            '-crf', '18',
            '-r', '30',
            '-movflags', '+faststart',
            '-y',  # 覆盖输出文件
            output_path
        ]

        # 3. 执行命令（带进度回调）
        print("执行命令:", " ".join(cmd))
        process = subprocess.Popen(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            universal_newlines=True
        )

        # 4. 处理进度更新
        for line in process.stdout:
            if progress_callback and 'time=' in line:
                try:
                    time_str = line.split('time=')[1].split()[0]
                    h, m, s = map(float, time_str.split(':'))
                    current_sec = timedelta(hours=h, minutes=m, seconds=s).total_seconds()
                    progress = min((current_sec / duration) * 100, 100)
                    progress_callback(progress)
                except:
                    continue

        process.wait()
        
        # 5. 验证输出
        if not os.path.exists(output_path):
            raise Exception("输出文件未生成")
            
        return True

    except subprocess.CalledProcessError as e:
        raise Exception(f"FFmpeg处理失败: {e.stderr}")
    except Exception as e:
        raise Exception(f"视频处理错误: {str(e)}")
